<?php

namespace Lib\Model;

class OnlineUsersModel {
   
    static function setOnline() {
        try{
        $b = \Lib\Database::getConnection()->prepare("
            delete from online_users
            where timestamp < :timestamp");
        $b->bindValue("timestamp", time() - 60*5, \PDO::PARAM_INT);
        $b->execute();    
        $b = \Lib\Database::getConnection()->prepare("
            insert
            into online_users(sess_id, timestamp, username)
            values(:sess_id,:timestamp,:username)
            ON DUPLICATE KEY UPDATE sess_id = :sess_id, timestamp = :timestamp, username = :username");
        $b->bindValue("sess_id", session_id(), \PDO::PARAM_STR);
        $b->bindValue("timestamp", time(), \PDO::PARAM_INT);
        $b->bindValue("username", (isset($_SESSION['user']) && !empty($_SESSION['user'])) ? $_SESSION['user'] : NULL, \PDO::PARAM_STR);
        $b->execute();
        return TRUE;
        } catch(\Exception $e){
           return FALSE;
        }
    }
    
    static function getOnline() {
        try{
        $b = \Lib\Database::getConnection()->prepare("
            select username, sess_id from online_users
            order by username");
        $b->execute();
        $users = $b->fetchAll(\PDO::FETCH_ASSOC);
        return $users;
        } catch(\Exception $e){
           return FALSE;
        }
    }
}

?>
